<template>
    <div class="yizhan">
        <h1>驿站管理</h1>
        <div class="input">
            <div>
                <span>驿站名称：</span>
                <el-input class="shuru" v-model="inputmendain" placeholder="请输入驿站名称">{{inputmendain}}</el-input>
            </div>
            <div>
                <span>小区名称：</span>
                <el-input class="shuru" v-model="mendainphone" placeholder="请输入小区名称">{{mendainphone}}</el-input>
            </div>

            <div class="block">
                <span class="demonstration">添加时间：</span>
                <el-date-picker
                        v-model="value1"
                        type="daterange"
                        range-separator="至"
                        start-placeholder="开始日期"
                        end-placeholder="结束日期">

                </el-date-picker>
                <el-button style="margin-left: 10px" @click="search" type="primary">搜索</el-button>
            </div>
        </div>

        <el-button type="primary" style="margin-bottom:20px" @click="dialogFormVisible = true">门店新增</el-button>

        <el-dialog title="驿站名字" :visible.sync="dialogFormVisible">
            <el-form :model="form">
                <el-form-item label="驿站名字" :label-width="formLabelWidth">
                    <el-input v-model="form.mendianname" autocomplete="off">{{form.mendianname}}</el-input>
                </el-form-item>
                <el-form-item label="驿站图片" :label-width="formLabelWidth">
                    <div style="height: 40px">
                        <el-upload
                                class="upload-demo"
                                action="/upload/image"
                                :show-file-list="false"
                                :on-success="handleUploadSuccess"
                                :before-upload="beforeUpload"

                        >
                            <div size="small" type="primary">+</div>
                        </el-upload>
                        <!--                        <el-input v-model="imageUrl" placeholder="请上传图片"></el-input>-->
                        <img v-if="imageUrl" :src="imageUrl" alt="Uploaded Image"
                             style="max-width: 100%; max-height: 200px;">
                    </div>
                </el-form-item>

                <el-form-item label="所属地区" :label-width="formLabelWidth">
                    <el-cascader
                            :options="addressAll"
                            clearable
                            v-model="address"
                            :props="{value:'label'}"
                    ></el-cascader>

                    <h1>{{address.join('')}}</h1>
                </el-form-item>

                <el-form-item :label-width="formLabelWidth">

                    <el-input v-model="form.date1" placeholder="请填写详细地址" autocomplete="off">{{form.date1}}</el-input>
                </el-form-item>

                <el-form-item label="所属小区" :label-width="formLabelWidth">

                    <el-select v-model="form.region" placeholder="请选择活动区域">
                        <el-option v-for="(v,key) in form.list" :key="key"
                                   :label="v.communityName"
                                   :value="v.communityId"
                        ></el-option>
                    </el-select>
                </el-form-item>

            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="dialogFormVisible = false">取 消</el-button>
                <el-button type="primary" @click="isok">确 定</el-button>
            </div>
        </el-dialog>
        <!--表格-->
        <template>
            <el-table
                    :data="tableData"
                    border
                    style="width: 100%"
                    :header-cell-style="{'background-color':'rgb(24, 144, 255)','color':'white','text-align':' center'}"
                    :cell-style="{'text-align':'center'}"
            >
                <el-table-column
                        fixed
                        prop="courierStationId"
                        label="ID"
                >
                </el-table-column>
                <el-table-column
                        fixed
                        prop="courierStationName"
                        label="驿站名字"
                >
                </el-table-column>
                <el-table-column
                        prop="courierStationImage"
                        label="驿站照片"
                >
                </el-table-column>
                <el-table-column
                        prop="courierStationAddress"
                        label="驿站地址"
                >
                    <template slot-scope="scope">
                        <div style="margin: 10px">
                            {{fun1(scope.row)}}
                        </div>
                    </template>
                </el-table-column>
                <el-table-column
                        prop="courierStationCommunityName"
                        label="所在小区"
                >

                </el-table-column>
                <el-table-column
                        prop="courierStationOrderCount"
                        label="订单总数"
                >
                </el-table-column>

                <el-table-column
                        prop="addTime"
                        label="添加时间"
                >
                </el-table-column>


                <el-table-column
                        fixed="right"
                        label="状态"
                        prop="courierStationStatus"
                >
                    <template slot-scope="scope1">
                        <span 　class="el-tag el-tag--success el-tag--medium el-tag--light"
                              v-if="scope1.row.courierStationStatus==1">上架</span>
                        <span 　class="el-tag el-tag--danger el-tag--medium el-tag--light" v-else>下架</span>

                    </template>
                </el-table-column>


                <el-table-column
                        fixed="right"
                        label="操作"
                        prop="courierStationSort"
                >
                    <template slot-scope="scope2">

                        <el-button type="text" size="small" @click="upDown(scope2.row)"
                                   v-if="scope2.row.courierStationStatus==1">
                            立即下架
                        </el-button>
                        <el-button type="text" size="small" @click="upDown(scope2.row)"
                                   v-else>
                            立即上架
                        </el-button>

                        <el-button type="text" size="small" @click="bianjixiaoquIndex(scope2.row)">编辑
                        </el-button>
                    </template>
                </el-table-column>
            </el-table>
        </template>


        <el-dialog title="驿站名字" :visible.sync="bianjixiaoqu">
            <el-form :model="form2">
                <el-form-item label="驿站名字" :label-width="formLabelWidth">
                    <el-input v-model="form2.mendianname" autocomplete="off">{{form2.mendianname}}</el-input>
                </el-form-item>
                <el-form-item label="驿站图片" :label-width="formLabelWidth">
                    <div style="height: 40px">
                        <el-upload
                                class="upload-demo"
                                action="/upload/image"
                                :show-file-list="false"
                                :on-success="handleUploadSuccess"
                                :before-upload="beforeUpload"

                        >
                            <div size="small" type="primary">+</div>
                        </el-upload>
                        <!--                        <el-input v-model="imageUrl" placeholder="请上传图片"></el-input>-->
                        <img v-if="imageUrl" :src="imageUrl" alt="Uploaded Image"
                             style="max-width: 100%; max-height: 200px;">
                    </div>
                </el-form-item>

                <el-form-item label="所属地区" :label-width="formLabelWidth">
                    <el-cascader
                            :options="addressAll"
                            clearable
                            v-model="form2.address"
                            :props="{value:'label'}"
                    ></el-cascader>

                    <h1>{{form2.address.join('')}}</h1>
                </el-form-item>

                <el-form-item :label-width="formLabelWidth">
                    <el-input v-model="form2.date1" placeholder="请填写详细地址" autocomplete="off">{{form2.date1}}</el-input>
                </el-form-item>

                <el-form-item label="所属小区" :label-width="formLabelWidth">
                    <el-select v-model="CommunityId" placeholder="">
                        <el-option v-for="(v,key) in form.list" :key="key"
                                   :label="v.communityName"
                                   :value="v.communityId"
                        ></el-option>
                    </el-select>
                </el-form-item>

            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="bianjixiaoqu = false">取 消</el-button>
                <el-button type="primary" @click="bianjixiaoqubaocun">确 定</el-button>
            </div>
        </el-dialog>

        <el-pagination
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
                :current-page="currentPage"
                :page-sizes="[5,10, 20, 30, 50]"
                :page-size="pageSize"
                layout="total, sizes, prev, pager, next, jumper"
                :total="total">
        </el-pagination>
    </div>
</template>

<script>
    export default {
        name: "yizhanComponent",
        data() {
            return {
                inputmendain: "",
                mendainphone: '',
                mendainStationStatus: '',
                pickerOptions: {
                    shortcuts: [{
                        text: '最近一周',
                        onClick(picker) {
                            const end = new Date();
                            const start = new Date();
                            start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
                            picker.$emit('pick', [start, end]);
                        }
                    }, {
                        text: '最近一个月',
                        onClick(picker) {
                            const end = new Date();
                            const start = new Date();
                            start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
                            picker.$emit('pick', [start, end]);
                        }
                    }, {
                        text: '最近三个月',
                        onClick(picker) {
                            const end = new Date();
                            const start = new Date();
                            start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
                            picker.$emit('pick', [start, end]);
                        }
                    }],
                },
                value1: '',
                value2: '',


                imageUrl: '',
                dialogFormVisible: false,
                bianjixiaoqu: false,
                form: {
                    mendianname: '',
                    phonee: '',
                    openingHours: "",
                    region: '',
                    date1: '',
                    date2: '',
                    delivery: false,
                    type: [],
                    resource: '',
                    desc: '',
                    weizhi: '',
                },
                form2: {
                    mendianname: '',
                    phonee: '',
                    openingHours: "",
                    region: '',
                    date1: '',
                    date2: '',
                    delivery: false,
                    type: [],
                    resource: '',
                    desc: '',
                    weizhi: '',
                    address: [],
                    pos: "",
                },
                formLabelWidth: '120px',

                addressAll: [],   //省市区
                address: [], //你选择的地址

                upDownArr: ["全部门店", "上架中", "已下架"],
                index: 0,
                weizhi1: "",
                weizhi2: "",
                weizhi3: "",
                weizhi4: "",
                id: "",
                CommunityId: "",
                Sort: 1,
                Status: 1,
                upDownStatus: "立即上架",


                tableData: [], // 表格数据
                currentPage: 1, // 当前页数
                pageSize: 5, // 每页条数
                total: 1,// 数据总数
                searchResults: [], // 存储搜索结果
            }
        },

        methods: {
            //获取省市
            getAllProvinceAndCityList() {
                // 获取全国所有省份和城市的列表
                var that = this;
                this.$http
                    .get("https://restapi.amap.com/v3/config/district", {
                        // 高德地图的API
                        params: {
                            key: "94214e26e4b0ec3a7d2ed9204f051583", // 这个是申请的 Key，读者自行写入
                            keywords: "中国",
                            subdistrict: 3,
                            extensions: "base",
                        },
                    })
                    .then((response) => {
                        console.log(response.data)
                        for (let i = 0; i < response.data.districts[0].districts.length; i++) {
                            let provinceMap = new Map();
                            provinceMap.value = response.data.districts[0].districts[i].adcode;   //区域编号
                            provinceMap.label = response.data.districts[0].districts[i].name;     //省名称
                            provinceMap.children = [];
                            that.addressAll.push(provinceMap);  //添加省份
                            for (let j = 0; j < response.data.districts[0].districts[i].districts.length; j++) {
                                let cityMap = new Map()
                                cityMap.value = response.data.districts[0].districts[i].districts[j].adcode;   //区域编号
                                cityMap.label = response.data.districts[0].districts[i].districts[j].name;     //市名称
                                cityMap.children = [];
                                provinceMap.children.push(cityMap); //添加市
                                for (let k = 0; k < response.data.districts[0].districts[i].districts[j].districts.length; k++) {
                                    let areaMap = new Map()
                                    areaMap.value = response.data.districts[0].districts[i].districts[j].districts[k].adcode;   //区域编号
                                    areaMap.label = response.data.districts[0].districts[i].districts[j].districts[k].name;     //区县名称
                                    cityMap.children.push(areaMap);   //添加区县
                                }
                            }
                        }
                    });
            },

            search() {
                if (!this.value1) {
                    this.value1 = "";
                }
                this.constructor = 1;
                this.axios.get("/courierStation/querySearchCourierStationList?", {

                    params: {
                        pageNum: this.currentPage,
                        pageSize: this.pageSize,
                        communityName: this.mendainphone,
                        courierStationStatus: "",
                        startTime: this.getDateString(this.value1[0]),
                        endTime: this.getDateString(this.value1[1]),
                        courierStationName: this.inputmendain,
                    }
                }).then(res => {
                    this.tableData = res.data.list;
                    this.total = res.data.total;
                }).catch(err => {
                    "错误"
                })

            },
            getDateString(date) {
                // let str = date.getFullYear() + "-" + (date.getMonth() + 1) + "-" + date.getDate() + " 00:00:00";
                // return str;
                if (!date) {
                    return ""
                }
                const year = date.getFullYear();
                const month = String(date.getMonth() + 1).padStart(2, '0');
                const day = String(date.getDate()).padStart(2, '0');
                const hours = String(date.getHours()).padStart(2, '0');
                const minutes = String(date.getMinutes()).padStart(2, '0');
                const seconds = String(date.getSeconds()).padStart(2, '0');
                return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
            },

            isok() {
                this.axios.post("/courierStation/addCourierStation",
                    {
                        courierStationAddress: this.form.date1,
                        courierStationCity: this.address[1],
                        courierStationCommunityId: "",
                        courierStationDistrict: this.address[2],
                        courierStationImage: "",
                        courierStationName: this.form.mendianname,
                        courierStationProvince: this.address[0],

                    }
                ).then(res => {
                    this.shujuAll();
                }).catch(err => {
                })
                this.dialogFormVisible = false;
            },
            shujuAll() {
                this.axios.get("/courierStation/querySearchCourierStationList?" + "pageNum=" + this.currentPage + "&pageSize=" + this.pageSize + "&courierStationName=&communityName=&courierStationStatus=&startTime=&endTime=").then(res => {
                    this.tableData = res.data.list;
                    this.total = res.data.total;

                    console.log(this.tableData)
                    // console.log(res.data);
                }).catch(err => {
                });
            },

            //点击切换上下架
            upDown(row) {
                let sta = "";
                if (row.courierStationStatus === 1) {
                    sta = 0;
                } else {
                    sta = 1;
                }
                this.axios.post("/courierStation/modifyCourierStation", {
                    courierStationId: row.courierStationId,
                    courierStationStatus: sta
                }).then(res => {
                    this.shujuAll()
                }).catch(e => {
                })
            },
            fun1(row) {
                return row.courierStationProvince + row.courierStationCity + row.courierStationDistrict + row.courierStationAddress
            },
            listArr() {
                this.axios.get("/community/communityList",{}).then(res=>{
                    this.form.list=res.data.data.list;
                    console.log(this.form.list)
                }).catch(err=>{})
            },

            //编辑
            bianjixiaoquIndex(index) {
                // console.log(this.form)
                this.form2.mendianname = index.courierStationName;
                // console.log(this.xiaoquguanli);
                this.form2.address = (index.courierStationProvince + "," + index.courierStationCity + "," + index.courierStationDistrict).split(",")
                // console.log(this.form2.address);
                this.form2.date1 = index.courierStationAddress;
                // // console.log(this.addmess);
                // this.form2.pos = index.shopLatitude + "," + index.shopLongitude;
                // console.log(this.form2.pos);
                // this.form2.phonee = index.shopPhone;
                // this.form2.openingHours = index.shopDescribe;
                this.form2.region = null;
                this.form2.date2 = index.addTime;
                this.id = index.courierStationId;
                this.CommunityId = index.courierStationCommunityId;
                this.Sort = index.courierStationSort;
                this.Status = index.courierStationStatus;

                this.bianjixiaoqu = true;

            },
            bianjixiaoqubaocun() {
                this.axios.post("/courierStation/modifyCourierStationServlet",
                    {
                        addTime: this.form2.date2,

                        courierStationAddress: this.form2.date1,
                        courierStationCity: this.form2.address[1],
                        courierStationCommunityId: this.CommunityId,
                        courierStationCommunityName: null,
                        courierStationDistrict: this.form2.address[2],
                        courierStationId: this.id,
                        courierStationImage: null,
                        courierStationName: this.form2.mendianname,
                        courierStationOrderCount: 0,
                        courierStationProvince: this.form2.address[0],
                        courierStationSort: this.Sort,
                        courierStationStatus: this.Status,

                    }
                ).then(() => {
                    this.bianjixiaoqu = false;
                    this.shujuAll();
                }).catch(err => {
                    "错误1"
                })
            },

            handleUploadSuccess(response, file) {
                // 处理上传成功后的响应，这里假设上传成功后返回图片的URL或者路径
                this.imageUrl = response.imageUrl; // 假设服务器返回的数据中包含 imageUrl 字段
            },
            beforeUpload(file) {
                // 可以在这里对文件进行大小、类型等验证
                const isJPG = file.type === 'image/jpeg';
                const isPNG = file.type === 'image/png';
                if (!isJPG) {
                    this.$message.error('上传图片只能是 JPG 格式!');
                    return false;
                }
                const isLt2M = file.size / 1024 / 1024 < 2;
                if (!isLt2M) {
                    this.$message.error('上传图片大小不能超过 2MB!');
                    return false;
                }
                return true; // 返回 true 允许上传，返回 false 则取消上传
            },


            // 切换每页条数
            handleSizeChange(size) {
                this.pageSize = size;
                // 可以在这里重新获取数据

                this.shujuAll()
            },
            // 切换当前页
            handleCurrentChange(page) {
                this.currentPage = page;
                // 可以在这里重新获取数据
                // this.axios.get("/courierStation/querySearchCourierStationList?", {
                //     params: {
                //         pageNum: this.currentPag,
                //         pageSize: this.pageSize,
                //         communityName: this.mendainphone,
                //         courierStationStatus: "",
                //         startTime: this.getDateString(this.value1[0]),
                //         endTime: this.getDateString(this.value1[1]),
                //         courierStationName: this.inputmendain,
                //     }
                // }).then(res => {
                //     this.tableData = res.data.list;
                //     this.total = res.data.total;
                //
                // }).catch(err => {
                //     "错误"
                // })
                this.search();

            },

        },
        computed: {},

        created() {
            this.shujuAll();
            this.getAllProvinceAndCityList();
            this.listArr();

        }
    }
</script>

<style scoped>
    .yizhan {
        /*height: 800px;*/
        /*background-color: greenyellow;*/
        padding: 20px;
    }


    .input {
        display: flex;
        flex-wrap: wrap;
        justify-content: left;
    }

    .input > div {
        margin: 20px 0;
    }

    span {
        font-size: 16px;
    }

    .shuru {
        width: 200px;
        height: 36px;
        padding: 0 15px;

    }
</style>